<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\OrderComment;
use App\Models\Product;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    public static $model;
    public function __construct()
    {
        self::$model = new Product();
    }

    //返回banner商品
    function is_banner() {
        $products =  Product::where('is_banner','>',0)->where('miaosha_end','>',date('Y-m-d H:i:s'))
                            ->orderBy('is_banner','desc')->orderBy('id','desc')->get()->toArray();
        return $this->response(0,$products);
    }
    //列表商品数据
    function list(Request $request){
        $request->validate([
            'keyword'   =>  'sometimes|string',
            'cid'       =>  'sometimes|integer',    // 栏目id
            'page'      =>  'required|integer',     //页码
            'type'      =>  'sometimes',     //页码
        ]);
        $keyword = $request->get('keyword');
        $cid = $request->get('cid') ;
        $page = $request->get('page') ?? 1;
        $offset = ($page - 1) * LIMIT;

        $whereIn = [];
        $where = [];
        if($cid > 0){
            $category_ids = Category::where('parent_id', $cid)->pluck('id')->toArray();
            $category_ids[] = $cid;
            $category_ids = array_unique($category_ids);
            $whereIn = $category_ids;
        }
        if ($keyword){
            $where[] = ['products.title' , 'like' , '%' .$keyword . '%'];
        }
        if ($type = $request->get('type')) {
            $where[] = ['type', '=', $type];
        }
        //$products = $this->get_products($where, $whereIn, $offset, LIMIT);
        $products = self::$model->get_products($where, $whereIn, $offset, LIMIT);
//        foreach ($products as &$product) {
//            $stock = 0;
//            $sold_prices = $origin_prices =[];
//            foreach ($product['skus'] as $key=>$sku) {
//                //计算该产品所有规格型号的累积销量和库存
//               // $sold_num += $sku['sold_num'];
//                $stock += $sku['stock'];
//                //把所有规格型号的售价组成数组
//                $sold_prices[$sku['id']] = $sku['sold_price'];
//                //把所有规格型号的原价组成数组
//                $origin_prices[] = $sku['origin_price'];
//            }
//            $product['skus_id'] = array_search(min($sold_prices),$sold_prices);
//            $product['min_sold_price'] = min($sold_prices);
//            $product['min_origin_price'] = min($origin_prices);
//            $product['stock'] = $stock;
//        }
        return $this->response(0,$products);
    }

    /**查询商品
     * @param array $where 条件查询数组
     * @param $whereIn
     * @param $offset
     * @param int $limit
     * @return  array
     */
    private function get_products($where, $whereIn, $offset, $limit) {
        $query = Product::query();
        $query->select('id','cover','title','sold_num');
        if ($where) {
            $query->where($where);
        }
        if ($whereIn) {
            $query->whereIn('category_id', $whereIn);
        }

        $products = $query->with(['skus'  =>  function($query){
            return $query->select("id","origin_price","sold_price","stock","show_sold_num as sold_num","product_id");
        }])->offset($offset)->limit($limit)->orderBy('products.id', 'desc')->get()->toArray();

        return $products;
    }

    //商品详情 todo  为了调试方便，暂时关闭表单验证
    function product(Request $request){
        $request->validate([
            'product_id'    =>  'required|integer',    // 商品id
            //'type1'     =>  'required|integer',
            //'choujiangid'  =>  'required|integer',
            //'role'      => 'required|integer',
            //'size'      => 'required|integer',        // 规格
            //'userid'    => 'required|integer',          //用户id
        ]);
        $size = $request->get('size',32);
        $product = Product::with(['skus'=>function($query){
            $query->withTrashed()
                  ->select("id", "title", "origin_price", "sold_price", "stock", "show_sold_num as sold_num", "product_id",'attributeValue');
        }])->withTrashed()->findOrFail($request->get('product_id'))->toArray();

//        foreach ($product['skus'] as  &$v){
//            //$product['sku'][$v['id']]=$v;
//        }
        //unset($product['skus']);

        $product['is_zhekou']=0;    //是否折扣
        $product['zhekou']=0;       //几折 尚未计算
        //1 新品  2 热销 3 推荐 4 特价
        if($product['type']==''){
            $product['xp']=1;
        }else{
            $type=explode(',',$product['type']);
            if(in_array(1,$type)){
                $product['xp']=1;
            }
            if(in_array(2,$type)){
                $product['rexiao']=1;
            }
            if(in_array(3,$type)){
                $product['tuijian']=1;
            }
            if(in_array(4,$type)){
                $product['is_zhekou']=1;
            }
        }
        unset($product['type']);

        //显示价格根据规格id调取默认显示价格
//        $product['qj_price']=$product['skus'][$size]['sold_price'];
//        $product['qj_yprice']=$product['skus'][$size]['origin_price'];
//        $product['stock']=$product['skus'][$size]['stock'];

//        $product['qj_price']=10;
//        $product['qj_yprice']=10;
//        $product['stock']=10;

        $product['size'] = $size;    //默认规格id  原样传回
        //前端使用的补充字段 可能需要加上
        $product['pro_number'] = 'okokok';   //商品编号
        $product['comments'] = [];    //评论
        $product['collection_id'] = '';
        $product['choujiangid'] = '';//抽奖id
        $product['attrList'] = [];
        /*$product['price11']=10.00; // 拼团价
        $product['price_yh']=10.00; // 优惠价*/

        $product['type01'] = '';    // 未知
//        print_r($product);exit;
        return $this->response(0,$product);
    }

    //商品结算,可能传的是购物车id或者商品id
    public function settlement(Request $request) {
        $request->validate([
            'product_id'    => 'sometimes|integer',    // 商品id
            'sku_id'        => 'sometimes|integer',        // 规格id
            'cart_id'       => 'sometimes|integer',          //购物车id
            'api_token'     => 'sometimes|string',          //有传购物车id时，必须验证token
            'buynum'        => 'sometimes|integer'         //购买数量
        ]);
        $products = [];

        if ($request->has('product_id')) {
            $product_id = $request->get('product_id');
            $sku_id = $request->get('sku_id');

            $products = Product::with(['skus'=>function($query) use ($sku_id) {
                $query->where('id',$sku_id)->select("id", "title", "origin_price", "sold_price", "product_id");
            }])->where('id',$product_id)->get()->toArray();

        }else if($request->has('cart_id')) {

        }

        //return $this->response(0,$products);

        //计算总价  todo    购物车时要乘以购物车中的商品数量
        if ($products) {
            $total_price = 0;
            foreach ($products as $product) {
                foreach ($product['skus'] as $sku) {
                    $total_price += $sku['sold_price'] * $request->get('buynum',1);
                }
            }
        }else {
            return $this->response(1,[],'商品信息错误');
        }

        return $this->response(0,['products' => $products,'total_price' => number_format($total_price,2),'coupon_money' => number_format($total_price,2)]);
    }

    //商品评价
    function comment_list(Request $request): JsonResponse {
        $request->validate([
            'product_id'    =>  'required|integer',    // 商品id
            'page_index'    =>  'integer'
        ]);
        $model = OrderComment::query();
        $res = $model->leftJoin('order_products','order_comments.order_id','=','order_products.order_id')
//            ->leftJoin("")
            ->distinct()->where(
                [
                    "order_products.product_id" => $request->get("product_id"),
                    "order_comments.status"     => 2
                ]
            )
            ->select('order_comments.id','order_comments.content','order_comments.created_at')
            ->orderBy('order_comments.id','desc')->paginate(100);
        $data = [
//            'count' => $res->total(),
            'data'  => $res->items(),
        ];
        foreach ($res->items() as $item) {
//            $item['CommentType'] = 'GOOD';
//            $item['CommentType'] = 'NOTBAD';
//            $item['CommentType'] = 'BAD';
        }
        return $this->response(0,$res->items());
    }
}
